How to sort the generic SortedList in descending order?
How to sort the generic SortedList in descending order?
17413-Jun-2024
Updated on 13-Jun-2024
Home / DeveloperSection / Forums / How to sort the generic SortedList in descending order?
How to sort the generic SortedList in descending order?
Ashutosh Kumar Verma
13-Jun-2024Sorting SortedList into Descending Order
The
SortedList<TKey, TValue>
class in C# does not have a built-in method to sort its elements directly in descending order. However, you can do this by creating a new list or collection and sorting the items from the original SortedList in order with it.Example-
Here a basic example to sort the SortedList into descending order in c#,
In the above exaple-
We first create a sortedList called
SortedList<int, string>
and add some items to it.We then create a
List<KeyValuePair<int, string>>
named descendingList for Descending order and ascendingList for Ascending order, and initialize it with the items from the original SortedList.We use the
Sort
method of the List class to sort the items in descending order based on the key. We provide a custom comparison function using a lambda expression.Finally, we print the orders.
Output-
This will print the items from the original SortedList in descending order of their key.
Also, Read: How to write file using StreamWriter in C#?